<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { ElTree, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { eachTree } from '@/utils/tree'
import { findIndex } from '@/utils'
import DeptApi from '@/api/dept'
const { required } = useValidator()
const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})
const handleSelect = (item: string) => {
  console.log(FormSchemas[3].hidden)
  if (item == '2') {
    FormSchemas[3].hidden = false
  } else {
    FormSchemas[3].hidden = true
  }
}
// 新增跟踪表单信息
const FormSchemas = reactive<FormSchema[]>([
  {
    field: 'roleName',
    label: '角色名称',
    component: 'Input',
    componentProps: {
      disabled: true
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'roleKey',
    label: '权限字符',
    component: 'Input',
    componentProps: {
      disabled: true
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'dataScope',
    label: '数据权限',
    component: 'Select',
    componentProps: {
      options: [
        {
          value: '1',
          label: '所有数据权限'
        },
        {
          value: '2',
          label: '自定义数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      on: {
        change: handleSelect
      }
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'deptIds',
    label: '数据权限',
    colProps: {
      span: 24
    },
    hidden: true,
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex w-full">
                <div class="flex-4">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="id"
                    highlight-current
                    expand-on-click-node={false}
                    data={treeData.value}
                    onNode-click={nodeClick}
                  >
                    {{
                      default: (data) => {
                        return <span>{data.data.label}</span>
                      }
                    }}
                  </ElTree>
                </div>
                <div class="flex-4">
                  {unref(currentTreeData) && unref(currentTreeData)?.permissionList ? (
                    <ElCheckboxGroup v-model={unref(currentTreeData).meta.permission}>
                      {unref(currentTreeData)?.permissionList.map((v: any) => {
                        return <ElCheckbox label={v.value}>{v.label}</ElCheckbox>
                      })}
                    </ElCheckboxGroup>
                  ) : null}
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])
if (props.currentRow.dataScope == '2') {
  FormSchemas[3].hidden = false
}
const treeRef = ref<typeof ElTree>()
const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  currentTreeData.value = treeData
}

const rules = reactive({
  roleName: [required()],
  roleKey: [required()],
  dataScope: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref<any>([])
const getMenuList = async () => {
  const res = await DeptApi.GetDeptListTree()
  if (res) {
    treeData.value = res.data
    if (!props.currentRow) return
    await nextTick()
    const checked: any[] = []
    if (props.currentRow.deptIds) {
      eachTree(props.currentRow.deptIds, (v) => {
        checked.push({
          id: v,
          permission: v.meta?.permission || []
        })
      })
      eachTree(treeData.value, (v) => {
        const index = findIndex(checked, (item) => {
          console.log(item)
          return item.id === v.id
        })
        if (index > -1) {
          const meta = { ...(v.meta || {}) }
          meta.permission = checked[index].permission
          v.meta = meta
        }
      })
      for (const item of checked) {
        unref(treeRef)?.setChecked(item.id, true, false)
      }
    }
  }
}
getMenuList()

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.dataScope == '2') {
      const checkedKeys = unref(treeRef)?.getCheckedKeys() || []
      formData.deptCheckStrictly = false
      formData.deptIds = checkedKeys || []
    }
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="FormSchemas" />
</template>

